﻿using System;
using System.Collections.Generic;
using System.Text;
using Enyim.Caching;
using Enyim.Caching.Memcached;
using System.Configuration;

namespace Huirui.Cavan.Core.Memcache
{
    public static class MemcachedHelper
    {
        internal static string _cachePoolName = ConfigurationManager.AppSettings["CachePoolName"];
        internal static string _keyTemplate = (_cachePoolName + "_{0}");
        internal static TimeSpan _maxExpiresAt = new TimeSpan(0, 43100, 0);
        internal static MemcachedClient mc = new MemcachedClient();

        public static object Get(string key)
        {            
            return mc.Get(string.Format(_keyTemplate, key));
        }

        public static T Get<T>(string key)
        {
            return mc.Get<T>(string.Format(_keyTemplate, key));
        }

        public static object Remove(string key)
        {
            return mc.Remove(string.Format(_keyTemplate, key));
        }

        public static void Store(string key, object value)
        {
            mc.Store(StoreMode.Set, string.Format(_keyTemplate, key), value);
        }

        public static void Store(string key, object value, DateTime expiresAt)
        {
            mc.Store(StoreMode.Set, string.Format(_keyTemplate, key), value, expiresAt);
        }

        public static void Store(string key, object value, TimeSpan expiresAt)
        {
            if (expiresAt > _maxExpiresAt)
            {
                expiresAt = _maxExpiresAt;
            }
            mc.Store(StoreMode.Set, string.Format(_keyTemplate, key), value, expiresAt);
        }
    }
}
